import Vue from 'vue'
import VueRouter from 'vue-router'
import routes from './routes'
import store from '@/store'
// 解决Vue-Router升级导致的Uncaught(in promise) navigation guard问题
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location, onResolve, onReject) {
  if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
  return originalPush.call(this, location).catch(err => err)
}
Vue.use(VueRouter)

const router = new VueRouter({
  routes
})
router.beforeEach((to, from, next) => {
  // 获取 vuex 中的定义的token
  const token = store.state.userToken.token
  // console.log(token)
  // 如果 没有获取到token 并且要跳转的路由页面 路径带 /user  就跳转到/login页面 并传参redirectUrl
  // 跳回登录的时候=》通过query参数带上当前跳转页面的地址——> 登陆成功后获取redirectUrl=》跳转到上次访问页面
  if (!token && to.path.startsWith('/user')) {
    next({
      path: '/login',
      query: { redirectUrl: to.path }
    })
  } else {
    next()
  }
})
export default router
